
/*!
	\file
	\brief Dialog with correspondence setting.

		\author Igor Mironchik (igor.mironchik at gmail dot com).

        Copyright (c) 2010 - 2011 Igor Mironchik

	Permission is hereby granted, free of charge, to any person
	obtaining a copy of this software and associated documentation
	files (the "Software"), to deal in the Software without
	restriction, including without limitation the rights to use,
	copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the
	Software is furnished to do so, subject to the following
	conditions:

	The above copyright notice and this permission notice shall be
	included in all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
	OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
	HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
	WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
	FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
	OTHER DEALINGS IN THE SOFTWARE.
*/

// eShopHelper include.
#include <eShopHelper/h/correspondence.hpp>
#include <eShopHelper/ui_correspondence.h>
#include <eShopHelper/h/document.hpp>

// Qt include.
#include <QtGui/QFileDialog>
#include <QtGui/QPushButton>
#include <QtGui/QStyledItemDelegate>
#include <QtGui/QComboBox>
#include <QtGui/QSortFilterProxyModel>

#include <QtCore/QStringList>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QAbstractTableModel>
#include <QtCore/QDebug>

namespace eShopHelper {

//
// CorrespondenceModel
//

//! Model for viewing correspondencies.
class CorrespondenceModel
	:	public QAbstractTableModel
{
	Q_OBJECT

public:
	CorrespondenceModel( QObject * parent = 0 )
		:	QAbstractTableModel( parent )
	{
	}

	int rowCount( const QModelIndex & parent = QModelIndex() ) const
	{
		if( parent.isValid() )
			return 0;
		else
			return m_data.size();
	}

	int columnCount( const QModelIndex & parent = QModelIndex() ) const
	{
		Q_UNUSED( parent );
		return 2;
	}

	QVariant data( const QModelIndex & index , int role ) const
	{
		if( !index.isValid() )
			return QVariant();

		if( index.row() >= m_data.size() || index.row() < 0 )
			return QVariant();

		if( role == Qt::DisplayRole )
		{
			QPair< QString, QString > pair = m_data.at( index.row() );

			if( index.column() == 0 )
				return pair.first;
			else if( index.column() == 1 )
				return pair.second;
		}

		return QVariant();
	}

	QVariant headerData( int section, Qt::Orientation orientation, int role ) const
	{
		if( role != Qt::DisplayRole )
			return QVariant();

		if( orientation == Qt::Horizontal )
		{
			switch( section )
			{
				case 0:
					return tr( "Excel file" );

				case 1:
					return tr( "Format" );

				default:
					return QVariant();
			}
		}

		return QVariant();
	}

	Qt::ItemFlags flags( const QModelIndex & index ) const
	{
		if( !index.isValid() )
			return 0;

		if( index.column() == 1 )
			return Qt::ItemIsEditable | Qt::ItemIsSelectable |
				Qt::ItemIsUserCheckable | Qt::ItemIsEnabled;
		else
			return Qt::ItemIsSelectable | Qt::ItemIsUserCheckable |
				Qt::ItemIsEnabled;
	}

	bool setData( const QModelIndex & index, const QVariant & value,
		int role = Qt::EditRole )
	{
		if( index.isValid() && role == Qt::EditRole )
		{
			int row = index.row();

			QPair< QString, QString > p = m_data.value( row );

			if( index.column() == 0 )
				p.first = value.toString();
			else if( index.column() == 1 )
				p.second = value.toString();
			else
				return false;

			m_data.replace( row, p );

			emit dataChanged( index, index );

			return true;
		}

		return false;
	}

	bool insertRows( int position, int rows,
		const QModelIndex & index = QModelIndex() )
	{
		Q_UNUSED( index );

		beginInsertRows( QModelIndex(), position, position + rows - 1 );

		for (int row = 0; row < rows; ++row )
		{
			QPair< QString, QString > pair( "", "" );
			m_data.insert( position, pair );
		}

		endInsertRows();

		return true;
	}

	bool removeRows( int position, int rows,
		const QModelIndex & index = QModelIndex() )
	{
		Q_UNUSED( index );

		beginRemoveRows( QModelIndex(), position, position + rows - 1 );

		for( int row = 0; row < rows; ++row )
		{
			m_data.removeAt( position );
		}

		endRemoveRows();

		return true;
	}

	void insertRow( const QString & excelFile,
		const QString & format )
	{
		insertRows( 0, 1 );

		setData( index( 0, 0 ), excelFile );
		setData( index( 0, 1 ), format );
	}

	QString excelFile( int row ) const
	{
		return m_data.at( row ).first;
	}

	QString format( int row ) const
	{
		return m_data.at( row ).second;
	}

private:
	//! Data of the model.
	QList< QPair< QString, QString > > m_data;
}; // class CorrespondenceModel


//
// ComboBoxDelegate
//

//! QListView item delegate.
class ComboBoxDelegate
	:	public QStyledItemDelegate
{
	Q_OBJECT

public:
	explicit ComboBoxDelegate( const QStringList & list,
		QObject * parent = 0 )
		:	QStyledItemDelegate( parent )
		,	m_list( list )
	{
	}

	QWidget * createEditor( QWidget * parent,
		const QStyleOptionViewItem & option,
		const QModelIndex & index ) const
	{
		Q_UNUSED( option );
		Q_UNUSED( index );

		QComboBox * editor = new QComboBox( parent );
		editor->addItems( m_list );

		return editor;
	}

	void setEditorData( QWidget * editor,
		const QModelIndex & index ) const
	{
		Q_UNUSED( editor );
		Q_UNUSED( index );
	}

	void setModelData( QWidget * editor, QAbstractItemModel * model,
		const QModelIndex & index ) const
	{
		QComboBox * comboBox = qobject_cast< QComboBox* >( editor );

		model->setData( index, comboBox->currentText(), Qt::EditRole );
	}

	void updateEditorGeometry( QWidget * editor,
		const QStyleOptionViewItem & option,
		const QModelIndex & index ) const
	{
		Q_UNUSED( index );

		editor->setGeometry( option.rect );
	}

private:
	//! List with a data for the delegate.
	QStringList m_list;
}; // class ComboBoxDelegate


//
// CorrespondenceDlg::PImpl
//

struct CorrespondenceDlg::PImpl {
	PImpl( const Document & doc )
		:	m_doc( doc )
		,	m_model( 0 )
		,	m_sortModel( 0 )
	{
	}

	//! UI.
	Ui::Dialog m_ui;
	//! Resultant document.
	Document m_doc;
	//! Model.
	CorrespondenceModel * m_model;
	//! Sort model.
	QSortFilterProxyModel * m_sortModel;
}; // struct CorrespondenceDlg::PImpl


//
// CorrespondenceDlg
//

CorrespondenceDlg::CorrespondenceDlg( const Document & doc,
	QWidget * parent, Qt::WindowFlags f )
	:	QDialog( parent, f )
	,	m_pimpl( new PImpl( doc ) )
{
	m_pimpl->m_ui.setupUi( this );

	init();
}

CorrespondenceDlg::~CorrespondenceDlg()
{
}

const Document &
CorrespondenceDlg::document() const
{
	return m_pimpl->m_doc;
}

void
CorrespondenceDlg::init()
{
	m_pimpl->m_model = new CorrespondenceModel( this );
	m_pimpl->m_sortModel = new QSortFilterProxyModel( this );
	m_pimpl->m_sortModel->setSourceModel( m_pimpl->m_model );

	ComboBoxDelegate * delegate =
		new ComboBoxDelegate( populateFormatFiles(), this );

	m_pimpl->m_ui.m_view->setItemDelegateForColumn( 1, delegate );
	m_pimpl->m_ui.m_view->setModel( m_pimpl->m_sortModel );

	for( Document::CorrepondenciesMap::ConstIterator
			it = m_pimpl->m_doc.correspondencies().begin(),
			last = m_pimpl->m_doc.correspondencies().end();
		it != last; ++it )
	{
		m_pimpl->m_model->insertRow( it.key(), it.value() );
	}

	m_pimpl->m_ui.m_view->resizeColumnToContents( 0 );
	m_pimpl->m_ui.m_view->sortByColumn( 0 );

	connect( m_pimpl->m_model,
		SIGNAL( dataChanged( const QModelIndex &, const QModelIndex & ) ),
		this, SLOT( slotItemContentChanged( const QModelIndex & ) ) );
}

QStringList
CorrespondenceDlg::populateFormatFiles()
{
	const QDir dir( c_formatFilesPath );

	const QFileInfoList files = dir.entryInfoList(
		QStringList() << QString::fromLatin1( "*.%1" )
			.arg( c_formatFileExtension ),
		QDir::Files );

	QStringList ret;

	foreach( const QFileInfo & info, files )
		ret << info.baseName();

	return ret;
}

void
CorrespondenceDlg::slotAdd()
{
	QFileDialog dlg( this, tr( "Select Excel files..." ),
		QString::fromLatin1( "./input" ),
		tr( "Excel files (*.xls)" ) );
	dlg.setFileMode( QFileDialog::ExistingFiles );

	if( QDialog::Accepted == dlg.exec() )
	{
		const QStringList excelFiles = dlg.selectedFiles();

		bool addedNewItem = false;

		foreach( const QString & excelFile, excelFiles )
		{
			if( !m_pimpl->m_doc.correspondencies().count( excelFile ) )
			{
				m_pimpl->m_doc.addCorrespondence( excelFile, QString() );

				m_pimpl->m_model->insertRow( excelFile, QString() );

				m_pimpl->m_ui.m_view->resizeColumnToContents( 0 );

				addedNewItem = true;
			}
		}

		if( addedNewItem )
		{
			m_pimpl->m_ui.m_ok->setEnabled( false );

			m_pimpl->m_ui.m_view->sortByColumn(
				m_pimpl->m_sortModel->sortColumn() );
		}
	}
}

void
CorrespondenceDlg::slotDel()
{
	QModelIndex index = m_pimpl->m_ui.m_view->currentIndex();

	if( index.isValid() )
	{
		m_pimpl->m_doc.delCorrepondence(
			m_pimpl->m_model->excelFile( index.row() ) );
		m_pimpl->m_model->removeRow( index.row(), QModelIndex() );

		if( m_pimpl->m_model->rowCount() == 0 )
		{
			m_pimpl->m_ui.m_delete->setEnabled( false );
			m_pimpl->m_ui.m_ok->setEnabled( false );
		}
		else
			checkCorrespondencies();
	}
}

void
CorrespondenceDlg::slotItemActivated( const QModelIndex & index )
{
	m_pimpl->m_ui.m_delete->setEnabled( true );
}

void
CorrespondenceDlg::slotItemContentChanged( const QModelIndex & index )
{
	if( index.isValid() )
	{
		const int row = index.row();

		m_pimpl->m_doc.correspondencies()[ m_pimpl->m_model->excelFile( row ) ] =
			m_pimpl->m_model->format( row );

		checkCorrespondencies();
	}
}

void
CorrespondenceDlg::checkCorrespondencies()
{
	for( Document::CorrepondenciesMap::ConstIterator
		it = m_pimpl->m_doc.correspondencies().begin(),
		last = m_pimpl->m_doc.correspondencies().end();
		it != last; ++it )
	{
		if( it.value().isEmpty() )
		{
			m_pimpl->m_ui.m_ok->setEnabled( false );
			return;
		}
	}

	m_pimpl->m_ui.m_ok->setEnabled( true );
}

} /* namespace eShopHelper */

#include "correspondence.moc"
